package com.citycloud.ccuap.tc.oauth2.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.citycloud.ccuap.tc.common.dto.DataCSecurityBasicUser;
import com.citycloud.ccuap.tc.common.result.ResultCodeEnum;
import com.citycloud.ccuap.tc.common.result.ResultObject;
import com.citycloud.ccuap.tc.oauth2.service.UserService;

@RestController
public class UserServiceController {

    @Autowired
    UserService userService;

    @Autowired
    private AuthorizationServerEndpointsConfiguration endpoints;

    @PostMapping("/sessionBased/userService/changePwd")
    public ResultObject<String> changePwd(Authentication authentication, String oldPwd, String newPwd) {
        DataCSecurityBasicUser user = (DataCSecurityBasicUser) authentication.getPrincipal();
        if (user == null) {
            return ResultObject.getInstance().error(ResultCodeEnum.TOKEN_UNAUTHORIZED, "未找到有效的用户凭证，请重新登陆再试。");
        }

        try {
            userService.changPwd(user, oldPwd, newPwd);
        } catch (RuntimeException e) {
            return ResultObject.getInstance().error(ResultCodeEnum.SUCCESSFUL_MSG, "原密码错误！");
        }

        return ResultObject.getInstance().success("成功", "密码更改成功");
    }

    @PostMapping("/nonSessionBased/userService/changePwd")
    public ResultObject<String> changePwdByToken(HttpServletRequest request, @RequestParam(value = "token", required = false) String value, String oldPwd, String newPwd) {

        if (value == null) {
            value = request.getHeader("accessToken");
        }
        if (value == null) {
            return ResultObject.getInstance().error(new InvalidTokenException("token不能为空"));
        }

        ResourceServerTokenServices resourceServerTokenServices = endpoints.getEndpointsConfigurer().getResourceServerTokenServices();
        //检测用户token是否有效
        OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
        if (token == null) {
            return ResultObject.getInstance().error(new InvalidTokenException("无效的token"));
        } else if (token.isExpired()) {
            return ResultObject.getInstance().error(new InvalidTokenException("过期的token"));
        } else {
            //获取用户ID
            OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());

            if (authentication.getUserAuthentication() == null) {
                return ResultObject.getInstance().error("该token(" + value + ")属于由客户端授权模式获取的token，不包含用户信息");
            }

            DataCSecurityBasicUser user = ((DataCSecurityBasicUser) authentication.getUserAuthentication().getPrincipal());

            if (user == null) {
                return ResultObject.getInstance().error(ResultCodeEnum.TOKEN_UNAUTHORIZED, "未找到有效的用户凭证，请重新登陆再试。");
            }

            try {
                userService.changPwd(user, oldPwd, newPwd);
            } catch (RuntimeException e) {
                return ResultObject.getInstance().error(ResultCodeEnum.SUCCESSFUL_MSG, "原密码错误！");
            }

            return ResultObject.getInstance().success("成功", "密码更改成功");
        }

    }

    @GetMapping("/loginCheck")
    public ResultObject<String> loginCheck(Authentication authentication) {
        String username = ((DataCSecurityBasicUser) authentication.getPrincipal()).getUserName();
        return ResultObject.getInstance().success("该用户已登陆", "欢迎！" + username + "，祝您有美好的一天。 ^-^");
    }

}
